import React, { useState } from 'react';
import { Button, Modal, Form, Input, Radio,Menu ,message } from 'antd';
import service from '../lib/service'
const Collections = ({ visible, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
        <Modal
            visible={visible}
            title="登录框"
            okText="登录"
            cancelText="取消"
            onCancel={onCancel}
            onOk={() => {
                form
                    .validateFields()
                    .then((values) => {
                        form.resetFields();
                        onCreate(values);
                    })
                    .catch((info) => {
                        console.log('Validate Failed:', info);
                    });
            }}
        >
            <Form
                form={form}
                layout="vertical"
                name="form_in_modal"
                initialValues={{
                    modifier: 'public',
                }}
            >
                <Form.Item
                    name="account"
                    label="账号"
                    rules={[
                        {
                            required: true,
                            message: '请输入账号',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    name="password"
                    label="密码"
                    rules={[
                        {
                            required: true,
                            message: '请输入密码',
                        },
                    ]}
                    hasFeedback
                >
                    <Input.Password />
                </Form.Item>
            </Form>
        </Modal>
    );
};

const Login = (props) => {
    const [visible, setVisible] = useState(false);
    const {setToken} = props;
    const onCreate = async (values) => {
        console.log('Received values of form: ', values);
        const result = await service.login(values);
        console.log(result)
        try{
            if(result.data.success == true){
                message.success('登录成功');
                let token = result.data.data.token;
                localStorage.setItem('dake-token',token);

                setToken(token)
            }
        }catch {
            message.error('登录失败');
        }
        setVisible(false);
    };

    return (
        <>
            <Button type="text" onClick={() => {
                setVisible(true);
            }}>登录
            </Button>
            <Collections
                visible={visible}
                onCreate={onCreate}
                onCancel={() => {
                    setVisible(false);
                }}
            />
        </>
    );
};
export default Login;